function [ ] = plotResidualDemand( obj, auction_id, bidder_code, ...
    figures, text, ceiling )
% plotResidualDemand Plot residual demand and smoothed version
%
% INPUTS:
%   obj : bidModel object
%   bi  : index for bid for which residual demand to be plotted

%   dr     : matrix of bid x tick x {p,qk} pairs where qk incremental
%   mcp    : vector of prices to plot, actual, then calculated
%   h      : bandwidth
%   invert : indicator variable for whether to smooth inverse residual 
%            demand or residual demand itself.  Smoothing residual demand, 
%            the bandwidth is in price units.  Smoothing inverse residual 
%            demand, the bandwidth is in quantity units.
%   Q      : aggregate quantity supplied by strategic firms

% Whether to add text box describing bid and equilibrium
if nargin < 5
    text = 0;
end

% Whether to plot ceiling tariff as part of demand bid
if nargin < 6
    ceiling = 0;
end

%% Formatting options
textProp = {'fontsize'    , 14, ...
            'FontName'    , 'Times New Roman'};
labProp  = {'fontsize'    , 14, ...
            'FontName'    , textProp{4}};

%% Preparation of data for plot

% Find index of bid for which to show residual demand
%   If no bidder code is passed . . . 
if isempty( bidder_code )
    bi = find(strcmp(auction_id,obj.sample.auction_id));
    fprintf(1,'Bidders at auction:\n');
    display(obj.sample(bi,{'auction_id','bidder_code','capacity_bid_mw'}));
    fprintf(1,'  Printing residual demand faced by %4.0f\n', ...
            obj.sample.bidder_code(bi(1)));
    bi = bi(1);
    
%   Or if a bidder code is passed . . . 
else
    bi = find(strcmp(auction_id,obj.sample.auction_id) & ...
        bidder_code == obj.sample.bidder_code);    
end

% Own bid
bidi = obj.bids(bi,:);

% Others' bids
auction_id_i = obj.sample.auction_id{bi};
bj   = strcmp(obj.sample.auction_id,auction_id_i);
bj(bi) = 0;
bidj = obj.bids(bj,:);

% Aggregate quantity
Qt = obj.sample.capacity_sought_mw(bi);

% Residual demand curve steps
bidj = sortrows(bidj,1,'ascend');

RDQ  = Qt - [0; cumsum(bidj(:,2))];
didx = kron([1:length(RDQ)]',[1; 1]);
RDQ  = RDQ( didx(1:end-1) );

RDP = [ bidj(didx(1:end-2),1) ];
RDP = [ 0; RDP ];

% Residual demand curve, smoothed
% pmin = 0;
pmin = floor((min([bidi(:,1); bidj(:,1)])-0.25)/1) * 1;
pmax = ceil((max([bidi(:,1); bidj(:,1)])+0.25)/0.5) * 0.5;
pgrid = [pmin:(pmax - pmin)/99:pmax]';

[ RDsmooth, ~ ] = RDtilde( pgrid, Qt, bidj, obj.hp );

% Own supply curve
QS = [ 0, 0; bidi(1), 0; bidi; pmax, bidi(2) ];


%% Plot residual demand, own supply and market clearing
f0 = figure;

h1 = plot(RDQ,RDP,'k-',...
         RDsmooth,pgrid,'b--',...
         'LineWidth',2);
hold on;
ylim([pmin pmax]);

xlabel('Quantity (MW)',textProp{:},'Interpreter','latex');
ylabel('Price (INR/kWh)',textProp{:},'Interpreter','latex');

titleString = sprintf('Residual Demand: Auction %s, Bidder %4.0f',...
    auction_id_i,bidder_code);
title(titleString,textProp{:},'Interpreter','latex');

% Figure formatting
set(gcf, 'Color'       , 'w' );
set(gca, labProp{:}, ...
         'Box'         , 'off'              , ...
         'LineWidth'   , 1.5                , ...
         'PlotBoxAspectRatio', [1 0.75 0.75]);  

% Own supply curve
h2 = plot(QS(:,2),QS(:,1),'r-','LineWidth',2);

% Vertical line at zero
h3 = plot([0,0],[pmin,pmax],'k-','LineWidth',1.5);
xl = xlim;

%% Add alternative residual demand curves that could have been realized
RDs = zeros(length(pgrid),obj.S);
fprintf(1,'Adding residual demand for simulation:\n');
for s = 1:obj.S
%    fprintf(1,'\t%3.0f',s);
%    if mod(s,10) == 0 
%        fprintf('\n');
%    end

   % Select indices of rivals j = {-i} from bid i's auction
   [ js ] = obj.pluckRivalsBysim( bi, s );

   % Calculate Qis quantity awarded and dQis/dP
   [ RDs(:,s), ~ ] = RDtilde( pgrid, Qt, obj.bids(js,:), obj.hp );
   
   % Add residual demand curve from one simulation to the plot
   plot(RDs(:,s),pgrid,'-','LineWidth',0.005,'Color',[0.005 0.005 0.005]);
end

hall = get(gca,'Children');
set(gca,'Children',[hall(end-3:end); hall(1:end-4)])
xlim(xl);
     
%% Legend 
legend([h1(1) h1(2) h2(1)],...
        'Residual demand',...
        'Residual demand (smoothed)',...
        'Own supply',...
        'Location','southoutside',...
        'Orientation','vertical',...
        'FontName','Times New Roman',...
        'fontsize',18);
legend boxoff;
hold off;

%% Export figure

% Crop whitespace 
fig = gcf;
fig.PaperPositionMode = 'auto';
fig_pos = fig.PaperPosition;
fig.PaperSize = [fig_pos(3) fig_pos(4)];

ax = gca;
outerpos = ax.OuterPosition;
ti = ax.TightInset;
left = outerpos(1) + ti(1);
bottom = outerpos(2) + ti(2);
ax_width = outerpos(3) - ti(1) - ti(3);
ax_height = outerpos(4) - ti(2) - ti(4);
ax.Position = [left bottom ax_width ax_height];

file = sprintf('/fig_resid_demand_%s_%04.0f.pdf',auction_id_i,bi);
filepath = [ figures file ];
fprintf(1,'Writing %s to file ...\n',filepath);
print(f0,'-dpdf','-painters','-noui','-r600',filepath);
fprintf(1,' complete.\n');

% clf;

end